#include<REG51.H>

unsigned char num[] = {0xC0, 0xF9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xd8, 0x80, 0x90};
unsigned char position = 0;
unsigned int tt = 0;
sbit key1 = P3^2;
sbit key2 = P3^3;
sbit _7seg4 = P1^0;
sbit _7seg3 = P1^1;
sbit _7seg2 = P1^2;
sbit _7seg1 = P1^3;

void display(unsigned int number); 
void delay(unsigned int a);
void init_timer();
void init_extlnt();

void main()
{
    init_timer();
    init_extlnt();
    while (1)
    {
        display(tt);
        delay(1000);
    }
}

void delay(unsigned int a)
{
    while (a--);
}

void init_timer()
{
    tt = 0;
    TMOD = 0X01;
    TH0 = (65536-10000)/256;
    TL0 = (65536-10000)%256;
    EA = 1;
    ET0 = 1;
    TR0 = 0;
}

void init_extlnt()
{
    EX0 = 1;
    IT0 = 1;
    EX1 = 1;
    IT1 = 1;
}

void timer() interrupt 1
{
    TH0 = (65536-10000)/256;
    TL0 = (65536-10000)%256;
    tt++;
    if(tt>9999) tt = 0;
}

void extlnt_0() interrupt 0
{
    tt = 0;
    TR0 = 1;
}

void extlnt_1() interrupt 2
{
    TR0 = 0;
}

void displlay(unsigned int number)
{
    P0 = 0XFF;
    _7seg1 = 0;
    _7seg2 = 0;
    _7seg3 = 0;
    _7seg4 = 0;
    switch (position)
    {
        case 0:
            _7seg4 = 1;
            P0 = num[number%10];
            break;
        case 1:
            _7seg3 = 1;
            P0 = num[number%100/10];
            break;
        case 2:
            _7seg2 = 1;
            P0 = num[number%1000/100]&0x7f;//decimal point
            break;
        case 3:
            _7seg1 = 1;
            P0 = num[number/1000];
            break;
    }
    position++;
    if(position>3) position = 0;
}